package aiingames.simulation.io;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aiingames.simulation.agent.State;


public class StateMapIO {

	public static Map<String,State> readStateMap(String file) {
		Map<String, State> map = new HashMap<String, State>();
		try {
			ObjectInputStream obs = new ObjectInputStream(new FileInputStream(file));
			@SuppressWarnings("unchecked")
			Collection<State> data = (Collection<State>) obs.readObject();
			obs.close();

			if (data != null) {
				for (State s : data) {
					map.put(s.toString(), s);
					//System.out.println(s);
				}
			}

		} catch (EOFException eof) {
			// eof.printStackTrace();

		} catch (IOException e) {
		 e.printStackTrace();
		 } catch (ClassNotFoundException e) {
		 e.printStackTrace();
		 }
		return map;
		// throw new RuntimeException("Could not read object from file");
	}

	public static void writeStateMap(String file, Map<String,State> data) {
		try {
			ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream(file));
			Collection<State> c = data.values();
			List<State> l = new ArrayList<State>(c);
			obs.writeObject(l);
			obs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}



	}

}
